package com.ycl.controller;

import com.alibaba.excel.util.FileUtils;
import com.ycl.dto.DevicesUploadDto;
import com.ycl.service.GeneratedService;
import com.ycl.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.imageio.*;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.List;

/**
 * @ClassName: GeneratedController
 * @Package: Image_synthesis
 * @Description: 生成类
 * @Author: sen.yang@youhualin.com
 * @Date: 2021/12/21 10:19
 * @Copyright: 德慧信息技术有限公司
 */
@RestController
@RequestMapping("/generated")
public class GeneratedController {

    @Autowired
    private GeneratedService generatedService;

    @Value("${ycl.path}")
    private String path;
    @Value("${ycl.url}")
    private String url;
    @Value("${ycl.domain_name}")
    private String domainName;

    @GetMapping(value = "/download")
    public void download(@RequestParam("name") String name) throws IOException {
        name = name + ".zip";
        File file = new File(path + "/" + name);
        if (!file.exists()) {
            return;
        }
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        // 设置信息给客户端不解析
        String type = new MimetypesFileTypeMap().getContentType(name);
        // 设置contenttype，即告诉客户端所发送的数据属于什么类型
        response.setHeader("Content-type", type);
        // 设置编码
        String hehe = new String(name.getBytes("utf-8"), "iso-8859-1");
        // 设置扩展头，当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
        response.setHeader("Content-Disposition", "attachment;filename=" + hehe);
        FileUtil.download(path + "/" + name, response);
        FileUtils.delete(file);
    }


    /**
     * 批量生成
     *
     * @param imgFile 背景图片
     * @param rgb     编码颜色
     * @param file    设备编码文件
     * @param top
     * @param left
     */
    @PostMapping("/batch")
    public String upload(@RequestParam("imgFile") MultipartFile imgFile, @RequestParam("file") MultipartFile file,
                         @RequestParam("rgb") String rgb, @RequestParam("fontSize") int fontSize,
                         @RequestParam("imgWidth") Double imgWidth,
                         @RequestParam("ewmWidth") Double ewmWidth, @RequestParam("ewmHeight") Double ewmHeight,
                         @RequestParam("top") Double top, @RequestParam("left") Double left, @RequestParam("type") String type) {
        String urlTem;
        if ("0".equals(type)) {
            urlTem = url+"%s";
        } else {
            urlTem =  url+"%s&type="+type;
        }
        String filename = imgFile.getResource().getFilename();
        try {
            List<DevicesUploadDto> uploadDtos = ExcelUtils.readExcel(file.getInputStream(), DevicesUploadDto.class, 1);
            //对背景图片进行裁剪
            // int imgWidth = 396;
            // int imgHeight = 441;
            InputStream inputStream = imgFile.getInputStream();
            Image src = NewImageUtils.read(inputStream);
            //图片类型
            String imgType = filename.split("\\.")[1];
            //背景宽
            int backWidth = src.getWidth(null);
            //缩放比例
            BigDecimal v = BigDecimal.valueOf(backWidth / imgWidth);
            top = v.multiply(BigDecimal.valueOf(top)).doubleValue();
            left = v.multiply(BigDecimal.valueOf(left)).doubleValue();
            ewmWidth = v.multiply(BigDecimal.valueOf(ewmWidth)).doubleValue();
            ewmHeight = v.multiply(BigDecimal.valueOf(ewmHeight)).doubleValue();
            fontSize = v.multiply(BigDecimal.valueOf(fontSize)).intValue();
            String[] split = rgb.split(",");
            Color color = new Color(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
            Font font = new Font("微软雅黑", Font.PLAIN, fontSize);
            int round = (int) Math.round(left);
            int round1 = (int) Math.round(top);
            Map<String, BufferedImage> imageInputStreams = new HashMap<>();
            for (DevicesUploadDto dto : uploadDtos) {
                BufferedImage read = ImageIO.read(imgFile.getInputStream());
                //设备码
                String code = dto.getCode();
                //设备码url
                String url = String.format(urlTem, code);
                //生成二维码
                int intEwmWidth = (int) Math.round(ewmWidth);
                int intEwmHeight = (int) Math.round(ewmHeight);
                QrCodeUtils qrCodeUtils=new QrCodeUtils();
                //生成二维码
                BufferedImage encode = qrCodeUtils.encode(url, "", false,intEwmWidth,intEwmHeight);

                BufferedImage buffImg = NewImageUtils.watermark(read, encode, round, round1, 1.0f);
                //计算字符串长度以找出中间位置
                Rectangle2D r = font.getStringBounds(code, new FontRenderContext(null, RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT, RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT));
                double width = r.getWidth();
                double height = r.getHeight();
                //添加编码
                NewImageUtils.addWaterMark(buffImg, round + getX(width, intEwmWidth), (int) (round1 + intEwmHeight+height*0.8), code, color, font);
                imageInputStreams.put(code, buffImg);
            }
            String uuid = UUID.randomUUID().toString();
            File file1 = new File(path);
            if(!file1.exists()){
                file1.mkdir();
            }
            ZipUtils.zipFile(path + "/" + uuid + ".zip", imageInputStreams, imgType);
            return uuid;
            //合成图片ImageIO
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private int getX(double width, int ewmWidth) {
        double v1 = width / 2;
        double v2 = ewmWidth / 2;
        return (int) Math.round(v2 - v1);
    }

    @GetMapping("/delete")
    public String delete() {
        generatedService.regularlyCleaned();
        return "清理成功";
    }

    @PostMapping("/deleteByName")
    public String deleteByName(@RequestParam("name") String name) {
        generatedService.deleteByName(name);
        return "清理成功";
    }

    @GetMapping("/getDomainName")
    public String getDomainName() {
        return domainName;
    }
}
